/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import com.oas.thit._this.balenq.xsd.BalanceEnquiryRequestBody;
import com.oas.thit._this.balenq.xsd.BalanceEnquiryResponseBody;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.transfer.xsd.TH2THTransferRequestBody;
import com.oas.thit._this.transfer.xsd.TH2THTransferResponseBody;
import com.oas.thit._this.queryacct.xsd.QueryAccountRequestBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit._this.xsd.THISResponseBody;
import com.oas.thit.hajj.xsd.RequestBody;
import com.oas.thit.xmlmessage.xsd.Header;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBElement;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.action.Wizard;
import net.sourceforge.stripes.controller.LifecycleStage;
import org.apache.commons.lang.StringUtils;
import th.manager.ResponseManager;
import th.manager.AkaunManager;
import th.model.Akaun;
import th.model.Deposit;
import th.model.Pengguna;
import th.stripes.BaseActionBean;
import th.stripes.Configuration;
import th.stripes.WelcomeActionBean;
import th.stripes.webservice.WebServiceUtil;
import org.apache.log4j.Logger;
import th.config.ableContextListener;
import th.dao.KodStatusDAO;
import th.dao.KodUrusanDAO;
import th.dao.SejarahTransaksiDAO;
import th.dao.THISutilDAO;
import th.manager.SMSgatewayManager;
import th.manager.SejarahTransaksiManager;
import th.model.AkaunFav;
import th.model.InfoAudit;
import th.model.KodKebenaranTransaksi;
import th.model.PindahanSimpanan;
import th.model.SejarahKatalaluan;
import th.model.SejarahTransaksi;
import th.model.THISutil;
import th.stripes.config.AuthRequired;
import th.stripes.util.AccCheckUtil;

/**
 *
 * @author fikri
 */
@AuthRequired
@HttpCache(allow = false)
@Wizard(startEvents = "Transfer_Step1")
@UrlBinding("/deposit/transfer")
public class TransferDepositAction extends BaseActionBean{
    
    private Pengguna pengguna;
    private List<Akaun> accountList;
    private Deposit deposit; 
    private List<AkaunFav> accFavList;
    private String noTel;
    private Date trxDate;
    
    
    @Inject
    private WebServiceUtil webUtil; 
    
    @Inject 
    private ResponseManager responseManager;    
    
    @Inject
    private AkaunManager akaunManager;
    
    @Inject
    SMSgatewayManager sMSgatewayManager;
    
    @Inject
    private SejarahTransaksiDAO sejarahTransaksiDAO;
    
    @Inject 
    private KodUrusanDAO kodUrusanDAO;
    
    @Inject
    private SejarahTransaksiManager sejarahTransaksiManager;
    
    @Inject 
    private KodStatusDAO kodStatusDAO;
    
    @Inject 
    private THISutilDAO tHISutilDAO;
    
    @Inject
    Configuration conf;
    
    private static String SUCCESSFUL = "0000";    
    private static String SYSTEM_ERROR = "9999";
    private static String INVALID_ACC_IC = "9000";
    private static String INSUFFICIENT_BALANCE = "8100";
    private static String BAL_ENQ_MSG_ID = "TPTH2TH3WD01";     
    private static String ACC_ENQ_MSG_ID = "TPTH2TH3WD02";
    private static String FND_TFR_MSG_ID = "TPTH2TH3WD03";     
    private static String HEADER_ID_BALANCE_ENQUIRY = "THSBENQ";     
    private static String HEADER_ID_ACC_ENQ = "THSQRAC"; 
    private static String HEADER_ID_FND_TFR= "THSTHT3";      
    private static String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";  
    
    
    private static Logger LOG = Logger.getLogger(DepositActionBean.class);
    
    @Before(stages= LifecycleStage.BindingAndValidation)
    public void rehydrate() {
        pengguna = getContext().getCurrentUser();
        
         
    }
       
    @DefaultHandler
    @HandlesEvent("Transfer_Step1")
    public Resolution selectAccount(){
        
        String responseCode = "";
        if (pengguna != null) {
            accountList = pengguna.getSenaraiAkaun();
            accFavList = pengguna.getSenaraiAkaunFav(); //update 24092014
            
        } else {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
        
        /*
         * Current : get No KP from table Akaun
         */
        deposit = new Deposit();
        deposit.setNoKp(pengguna.getNoKp());
        deposit.setNoAkaun(akaunManager.getNoAkaun(deposit.getNoKp(), "Y"));
        
        /**
         * Add 7/10/2014
         * checking if user have fav acc
         */
        if (pengguna.getSenaraiAkaunFav().isEmpty()) {
            return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
        } 
        
        /*
         *  To do : Get No KP from Core
         *  Added in on : 21/7/2014
         *
        
        try { // Call Web Service Operation
             com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
             com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
             // TODO initialize WS operation arguments here
             com.oas.thit._this.queryacct.xsd.QueryAccountRequest req = new com.oas.thit._this.queryacct.xsd.QueryAccountRequest();
             req.setHeader( webUtil.createHeader(ACC_ENQ_MSG_ID, HEADER_ID_ACC_ENQ) );
             
             com.oas.thit._this.queryacct.xsd.ObjectFactory objFactory = new com.oas.thit._this.queryacct.xsd.ObjectFactory();          
             QueryAccountRequestBody reqBody = objFactory.createQueryAccountRequestBody();
             reqBody.setTHAcct( objFactory.createQueryAccountRequestBodyTHAcct(deposit.getNoAkaun()));
             req.setBody( objFactory.createQueryAccountRequestBody(reqBody));
             // TODO process result here
             com.oas.thit._this.xsd.THISResponse result = port.queryAccount(req);
             Header header = result.getHeader().getValue();
             responseCode = header.getResponseCode().getValue();
             if ( responseCode.equals(SUCCESSFUL)) {
                 THISResponseBody res = result.getBody().getValue();
                 if ( res != null ) {
                     
                     
                     deposit.setNoKp(res.getTHICNo().getValue().trim());
                     deposit.setNoAkaun(res.getTHAcct().getValue().trim());
                 }
  
                 return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
             }
             addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));             
         } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));
         }
         */
        /*
         * 
         */
        
        
        //return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
        return new ForwardResolution("/WEB-INF/jsp/deposit/fund_transfer_main.jsp");
    }  
    
//    @HandlesEvent("Step2")
//    public Resolution selectToAccount() {
//        if (pengguna == null) {
//            return new RedirectResolution(WelcomeActionBean.class)
//                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
//        }
//        deposit.setNama(akaunManager.getNama(deposit.getNoAkaunDari()));
//        return new ForwardResolution("/WEB-INF/jsp/deposit/show_amount_to_tranfer.jsp");
//    }
    
    
    public Resolution showFund() {
        if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
        
        accountList = pengguna.getSenaraiAkaun();
        accFavList = pengguna.getSenaraiAkaunFav(); //update 24092014
        
        deposit.setNama(akaunManager.getNama(deposit.getNoAkaunDari()));
        deposit.setNoAkaun(deposit.getNoAkaun());
        deposit.setNoKp(deposit.getNoKp());
       // return new ForwardResolution("/WEB-INF/jsp/deposit/show_amount_to_tranfer.jsp");
        
        if (deposit.getJenisAkaun().equals("normal")) {
            return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
        } else {
            return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_fav.jsp");
        }
            
       
    }
    
    public Resolution checkFavAccTransfer() {
        
        AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);

        boolean check = checking.checkAccFav(deposit, pengguna); 
        
         if (!check) {
            addSimpleError("" + responseManager.getResponseMessage("9000", FND_TFR_MSG_ID));
            return new JSP("deposit/msg.jsp");
        }else {
             getContext().getRequest().getSession().setAttribute("deposit",deposit);
             selectAmountFav();
        }
        
        return new JSP("deposit/msg.jsp");
    }
    
    @HandlesEvent("Transfer_Step2")
    public Resolution selectAmount() {
        //todo web service     
        String responseCode = "";
         if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
         
        AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
        boolean check = checking.checkAcc(deposit, pengguna);     
        
        if (!check) {
            addSimpleError("" + responseManager.getResponseMessage("9000", FND_TFR_MSG_ID));
            return new JSP("deposit/msg.jsp");
        }
         
        Map <String , Object > map = validateAmaun(deposit.getNoAkaunDari(), deposit.getNoKp(), deposit.getAmaun());
         if ( map != null ) {
             boolean result = (Boolean) map.get("result");
             if (!result ) {
                addSimpleError((String) map.get("error"));
                return new JSP("deposit/msg.jsp");
             }
             
             BigDecimal bd =  (BigDecimal) map.get("bakiAmaun");
             deposit.setBalanceAmaun(bd);
         }
         
         //validation on maximum trx amt per day
         List<SejarahTransaksi> sejarahTransaksi = sejarahTransaksiManager.findSejarahTransaksiByCurrentDate(deposit.getNoKp());
         double amaun = 0;
         if(sejarahTransaksi!=null && sejarahTransaksi.size()>0){              
              for(int i = 0; i<sejarahTransaksi.size(); i++ ){
                
                  SejarahTransaksi st = sejarahTransaksi.get(i);
                  
                  if (StringUtils.isBlank(st.getDariAkaun())) continue;
                  
                  if(st.getDariAkaun().trim().equals(deposit.getNoAkaunDari())){
                      amaun = amaun + st.getAmaun().doubleValue();
                  }
                }    
          } 
          
          List acctList = pengguna.getSenaraiAkaun();
          boolean ownAcct = false;
          for(int i = 0; i<acctList.size(); i++ ){
              Akaun akaun = (Akaun)acctList.get(i);
              if(akaun.getAkaunTmbhn().trim().equals(deposit.getNoAkaunPenerima())){
                  ownAcct = true;
                  break;
              }              
          }
          
          if(ownAcct== true){
              amaun = amaun + deposit.getAmaun().doubleValue();
            if(amaun > 15000){
                accountList = pengguna.getSenaraiAkaun();
                addSimpleError("Amaun melebihi had yang dibenarkan(RM15000.00)");
                return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
            }
          }else{
              amaun = amaun + deposit.getAmaun().doubleValue();
            if(amaun > 5000){
                accountList = pengguna.getSenaraiAkaun();
                addSimpleError("Amaun melebihi had yang dibenarkan(RM5000.00)");
                return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer.jsp");
            }              
          }
          //end validataion
         
         try { // Call Web Service Operation
             com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
             com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
             // TODO initialize WS operation arguments here
             com.oas.thit._this.queryacct.xsd.QueryAccountRequest req = new com.oas.thit._this.queryacct.xsd.QueryAccountRequest();
             req.setHeader( webUtil.createHeader(ACC_ENQ_MSG_ID, HEADER_ID_ACC_ENQ) );
             
             com.oas.thit._this.queryacct.xsd.ObjectFactory objFactory = new com.oas.thit._this.queryacct.xsd.ObjectFactory();          
             QueryAccountRequestBody reqBody = objFactory.createQueryAccountRequestBody();
             reqBody.setTHAcct( objFactory.createQueryAccountRequestBodyTHAcct(deposit.getNoAkaunPenerima()));
             req.setBody( objFactory.createQueryAccountRequestBody(reqBody));
             // TODO process result here
             com.oas.thit._this.xsd.THISResponse result = port.queryAccount(req);
             Header header = result.getHeader().getValue();
             responseCode = header.getResponseCode().getValue();
             if ( responseCode.equals(SUCCESSFUL)) {
                 THISResponseBody res = result.getBody().getValue();
                 if ( res != null ) {
                     deposit.setNamaPenerima( res.getTHName().getValue() );
                     deposit.setNoAkaunPenerima( res.getTHAcct().getValue() );
                 }
  //               deposit.setNama(akaunManager.getNama(deposit.getNoAkaunDari()));
                 return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_TACrequest.jsp");
             }
             addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));             
         } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));
         }
        return new JSP("deposit/msg.jsp");
    }
    
    @HandlesEvent("Transfer_Step2Fav")
    public Resolution selectAmountFav() {
        //todo web service     
        String responseCode = "";
         if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
         
        AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
        boolean check = checking.checkAcc(deposit, pengguna);     
        
        if (!check) {
            addSimpleError("" + responseManager.getResponseMessage("9000", FND_TFR_MSG_ID));
            return new JSP("deposit/msg.jsp");
        }
         
        Map <String , Object > map = validateAmaun(deposit.getNoAkaunDari(), deposit.getNoKp(), deposit.getAmaun());
         if ( map != null ) {
             boolean result = (Boolean) map.get("result");
             if (!result ) {
                addSimpleError((String) map.get("error"));
                return new JSP("deposit/msg.jsp");
             }
             
             BigDecimal bd =  (BigDecimal) map.get("bakiAmaun");
             deposit.setBalanceAmaun(bd);
         }
         
         //validation on maximum trx amt per day
         List<SejarahTransaksi> sejarahTransaksi = sejarahTransaksiManager.findSejarahTransaksiByCurrentDate(deposit.getNoKp());
         double amaun = 0;
         if(sejarahTransaksi!=null && sejarahTransaksi.size()>0){              
              for(int i = 0; i<sejarahTransaksi.size(); i++ ){
                
                  SejarahTransaksi st = sejarahTransaksi.get(i);
                  
                  if (StringUtils.isBlank(st.getDariAkaun())) continue;
                  
                  if(st.getDariAkaun().trim().equals(deposit.getNoAkaunDari())){
                      amaun = amaun + st.getAmaun().doubleValue();
                  }
                }    
          } 
          
          List acctList = pengguna.getSenaraiAkaun();
          boolean ownAcct = false;
          for(int i = 0; i<acctList.size(); i++ ){
              Akaun akaun = (Akaun)acctList.get(i);
              if(akaun.getAkaunTmbhn().trim().equals(deposit.getNoAkaunPenerima())){
                  ownAcct = true;
                  break;
              }              
          }
          
          if(ownAcct== true){
              amaun = amaun + deposit.getAmaun().doubleValue();
            if(amaun > 15000){
                accountList = pengguna.getSenaraiAkaun();
                addSimpleError("Amaun melebihi had yang dibenarkan(RM15000.00)");
                return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_fav.jsp");
            }
          }else{
              amaun = amaun + deposit.getAmaun().doubleValue();
            if(amaun > 5000){
                accountList = pengguna.getSenaraiAkaun();
                addSimpleError("Amaun melebihi had yang dibenarkan(RM5000.00)");
                return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_fav.jsp");
            }              
          }
          //end validataion
         
         try { // Call Web Service Operation
             com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
             com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
             // TODO initialize WS operation arguments here
             com.oas.thit._this.queryacct.xsd.QueryAccountRequest req = new com.oas.thit._this.queryacct.xsd.QueryAccountRequest();
             req.setHeader( webUtil.createHeader(ACC_ENQ_MSG_ID, HEADER_ID_ACC_ENQ) );
             
             com.oas.thit._this.queryacct.xsd.ObjectFactory objFactory = new com.oas.thit._this.queryacct.xsd.ObjectFactory();          
             QueryAccountRequestBody reqBody = objFactory.createQueryAccountRequestBody();
             reqBody.setTHAcct( objFactory.createQueryAccountRequestBodyTHAcct(deposit.getNoAkaunPenerima()));
             req.setBody( objFactory.createQueryAccountRequestBody(reqBody));
             // TODO process result here
             com.oas.thit._this.xsd.THISResponse result = port.queryAccount(req);
             Header header = result.getHeader().getValue();
             responseCode = header.getResponseCode().getValue();
             if ( responseCode.equals(SUCCESSFUL)) {
                 THISResponseBody res = result.getBody().getValue();
                 if ( res != null ) {
                     deposit.setNamaPenerima( res.getTHName().getValue() );
                     deposit.setNoAkaunPenerima( res.getTHAcct().getValue() );
                 }
  //               deposit.setNama(akaunManager.getNama(deposit.getNoAkaunDari()));
                 //should x payah TAC number - kene tukar (31102014)
                 //return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_TACrequest.jsp");
                  getContext().getRequest().getSession().setAttribute("deposit",deposit);
                 return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_confirmation_fav.jsp");
             }
             addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));             
         } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));
         }
        return new JSP("deposit/msg.jsp");
    }
    
    private Map<String, Object> validateAmaun (String noAkaun, String ic, BigDecimal amaunToTransfer) {
        String responseCode = "";
        DecimalFormat formatter = new DecimalFormat("#,###,###.##");
        Map<String, Object> map = new HashMap<String,Object>();        
        try { // Call Web Service Operation
            com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
            com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit._this.balenq.xsd.BalanceEnquiryRequest req = new com.oas.thit._this.balenq.xsd.BalanceEnquiryRequest();           
            com.oas.thit._this.balenq.xsd.ObjectFactory objFactory = new com.oas.thit._this.balenq.xsd.ObjectFactory();          
            com.oas.thit._this.xsd.ObjectFactory _objFactory = new com.oas.thit._this.xsd.ObjectFactory(); 
           
            req.setHeader( webUtil.createHeader(BAL_ENQ_MSG_ID, HEADER_ID_BALANCE_ENQUIRY) ); 
            BalanceEnquiryRequestBody reqBody = objFactory.createBalanceEnquiryRequestBody(); 
            if (deposit.getNoKp().equals(deposit.getNoKpDari())) {                
                reqBody.setTHAcct(_objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaunDari()));
                reqBody.setTHICNo(_objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKpDari()));
            } else {
                reqBody.setParentAcct(objFactory.createBalanceEnquiryRequestBodyParentAcct(deposit.getNoAkaun()));
                reqBody.setParentICNo(objFactory.createBalanceEnquiryRequestBodyParentICNo(deposit.getNoKp()));
                reqBody.setTHAcct(_objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaunDari()));
                reqBody.setTHICNo(_objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKpDari()));
            } 
            
            JAXBElement<BalanceEnquiryRequestBody> jReqBody =  objFactory.createBalanceEnquiryRequestBody(reqBody);
            req.setBody(jReqBody);
            com.oas.thit._this.balenq.xsd.BalanceEnquiryResponse result = port.balanceEnquiry(req);            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                BalanceEnquiryResponseBody resp = result.getBody().getValue();
                deposit.setNama(resp.getTHName().getValue());
                BigDecimal amaun = new BigDecimal(resp.getTHAmount().getValue()).multiply(new BigDecimal("0.01"));
                
//                BigDecimal baki = new BigDecimal(formatter.format(amaun));                
               
                int f = amaun.compareTo(amaunToTransfer);
                if ( f < 0 ){
                    map.put("error", responseManager.getResponseMessage(INSUFFICIENT_BALANCE, ACC_ENQ_MSG_ID));
                    map.put("result", false);
                    return map;
                } else {                    
//                     BigDecimal balance = amaun.subtract(amaunToTransfer.multiply(new BigDecimal("0.01")));                 
                     BigDecimal balance = amaun.subtract(amaunToTransfer);                 
//                     BigDecimal bakiAmaun = new BigDecimal(formatter.format(balance));
                     deposit.setBalanceAmaun(balance);                     
                     map.put("bakiAmaun", balance);
                }   
            }else{
                addSimpleError("" + responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID));
                String errorRtn = responseManager.getResponseMessage(responseCode, ACC_ENQ_MSG_ID);
                map.put("error", errorRtn);                
                map.put("result", false);
                return map;               
            }
        }catch (Exception ex) {            
            map.put("error", ex);
            map.put("result", false);
            return map;
        }        
        map.put("result", true);
        return map;
    }

    
    @HandlesEvent("Transfer_Step3")
    public Resolution selectTac() {
        
        if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());
        
        HttpSession ses = context.getRequest().getSession();
        
        KodKebenaranTransaksi kodKebenaranTransaksi = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(ses.getId(), HEADER_ID_FND_TFR, "Y");
        if(kodKebenaranTransaksi != null){
            if(kodKebenaranTransaksi.getSah().equals("Y") && kodKebenaranTransaksi.getKodKebenaranTransaksi().equals(deposit.getTacNumber())){
                kodKebenaranTransaksi.setInfoAudit(ia);
                kodKebenaranTransaksi.setSah("N");
                sMSgatewayManager.saveTAC(kodKebenaranTransaksi);
                return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_confirmation.jsp");
            }               
        }
        addSimpleError("KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH");
        return new ForwardResolution("/WEB-INF/jsp/deposit/show_fund_transfer_TACrequest.jsp");
    }
    
    @HandlesEvent("Transfer_Step4")
    public Resolution completeTransfer() {
        //todo web service
        if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
        
        AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
        boolean check = checking.checkAcc(deposit, pengguna);
        
        if (!check) {
            addSimpleError("" + responseManager.getResponseMessage("9000", FND_TFR_MSG_ID));
            return new JSP("deposit/msg.jsp");
        }
        
        String responseCode = "";
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi(); 
        try {             
             com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
             com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
             com.oas.thit._this.transfer.xsd.TH2THTransferRequest req = new com.oas.thit._this.transfer.xsd.TH2THTransferRequest();             
             com.oas.thit._this.transfer.xsd.ObjectFactory objFactory = new com.oas.thit._this.transfer.xsd.ObjectFactory();
             req.setHeader( webUtil.createHeader(FND_TFR_MSG_ID, HEADER_ID_FND_TFR));
             TH2THTransferRequestBody reqBody = objFactory.createTH2THTransferRequestBody();             
             if(deposit.getNoKp().equals(deposit.getNoKpDari())){                
                 reqBody.setPayorAcct(objFactory.createTH2THTransferRequestBodyPayorAcct(deposit.getNoAkaunDari()));
                 reqBody.setPayorICNo(objFactory.createTH2THTransferRequestBodyPayorICNo(deposit.getNoKpDari()));             
             }else{            
                 reqBody.setParentAcct(objFactory.createTH2THTransferRequestBodyParentAcct(deposit.getNoAkaun()));
                 reqBody.setParentICNo(objFactory.createTH2THTransferRequestBodyParentICNo(deposit.getNoKp()));
                 reqBody.setPayorAcct(objFactory.createTH2THTransferRequestBodyPayorAcct(deposit.getNoAkaunDari()));
                 reqBody.setPayorICNo(objFactory.createTH2THTransferRequestBodyPayorICNo(deposit.getNoKpDari()));            
             }
                
             BigDecimal amt = deposit.getAmaun();
             amt = amt.multiply(new BigDecimal("100"));
             amt = new BigDecimal(amt.intValue());
             
             reqBody.setAmount(objFactory.createTH2THTransferRequestBodyAmount(amt.toString()));
             reqBody.setPayeeAcct(objFactory.createTH2THTransferRequestBodyPayeeAcct(deposit.getNoAkaunPenerima()));             
             JAXBElement<TH2THTransferRequestBody> jReqBody =  objFactory.createTH2THTransferRequestBody(reqBody);
             req.setBody(jReqBody);
             com.oas.thit._this.transfer.xsd.TH2THTransferResponse result = port.th2ThTransfer(req);             
             Header header = result.getHeader().getValue();
             responseCode = header.getResponseCode().getValue();             
                    
             sejarahTransaksi.setPengguna(pengguna);
             sejarahTransaksi.setTrhMasuk(new Date());
             sejarahTransaksi.setUrusan(kodUrusanDAO.findById(FND_TFR_MSG_ID));
             sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());
             sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
             sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue());
             if ( responseCode.equals(SUCCESSFUL)) {                 
                 TH2THTransferResponseBody res = result.getBody().getValue();
                   if(res != null){                    
                        String txid = header.getTxid().getValue();                       
                        deposit.setNoResit(header.getTxid().getValue().substring(9,25));                       
                        String dt = txid.substring(7, 21);                    
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        deposit.setTarikhTransaksi(dateFormat.parse(dt));
                        deposit.setStsPindahanDis(responseManager.getResponseMessage(SUCCESSFUL, FND_TFR_MSG_ID));
                                                
                        PindahanSimpanan pindahanSimpanan = new PindahanSimpanan();
                        pindahanSimpanan.setAmaun(deposit.getAmaun());
                        pindahanSimpanan.setStatus(deposit.getStsPindahanDis());
                        pindahanSimpanan.setTarikhTransaksi(deposit.getTarikhTransaksi());
                        pindahanSimpanan.setNoAkaunDari(deposit.getNoAkaunDari());
                        pindahanSimpanan.setNama(deposit.getNama());
                        pindahanSimpanan.setNamaPenerima(deposit.getNamaPenerima());
                        pindahanSimpanan.setNoAkaunPenerima(deposit.getNoAkaunPenerima());
                        pindahanSimpanan.setNoResit(deposit.getNoResit());
                        
                        sejarahTransaksi.setDariAkaun(deposit.getNoAkaunDari());
                        sejarahTransaksi.setKepadaAkaun(deposit.getNoAkaunPenerima());
                        sejarahTransaksi.setAmaun(deposit.getAmaun());
                        
                        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);  
                          
                        getContext().getRequest().getSession().setAttribute("PindahanSimpanan",pindahanSimpanan);
                         
                        return new JSP("deposit/show_fund_transfer_succesful_msg.jsp");
                }                
             }
              
             addSimpleError("" + responseManager.getResponseMessage(responseCode, FND_TFR_MSG_ID));  
         } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, FND_TFR_MSG_ID));
         } 
        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi); 
        return new JSP("deposit/msg.jsp");         
    }    
    
     //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    @HandlesEvent("Transfer_Fav")
    public Resolution transferFundFav() {
    
        completeTransferFav();
        if (deposit.getStatusTransfer().equals("success")) {
        
        }
        //sendNotify();
        
        return new JSP("deposit/msg.jsp");
    }
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    //added in 31102014
    @HandlesEvent("Transfer_Step4Fav")
    public Resolution completeTransferFav() {
        //todo web service
        if (pengguna == null) {
            return new RedirectResolution(WelcomeActionBean.class)
                    .addParameter("message", "Sila LOG MASUK terlebih dahulu untuk menggunakan perkhidmatan ini.");
        }
        
        AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
        
        boolean check = checking.checkAcc(deposit, pengguna);
        
        if (!check) {
            addSimpleError("" + responseManager.getResponseMessage("9000", FND_TFR_MSG_ID));
            return new JSP("deposit/msg.jsp");
        }
        
        String responseCode = "";
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi(); 
        try {             
             com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
             com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
             com.oas.thit._this.transfer.xsd.TH2THTransferRequest req = new com.oas.thit._this.transfer.xsd.TH2THTransferRequest();             
             com.oas.thit._this.transfer.xsd.ObjectFactory objFactory = new com.oas.thit._this.transfer.xsd.ObjectFactory();
             req.setHeader( webUtil.createHeader(FND_TFR_MSG_ID, HEADER_ID_FND_TFR));
             TH2THTransferRequestBody reqBody = objFactory.createTH2THTransferRequestBody();             
             if(deposit.getNoKp().equals(deposit.getNoKpDari())){                
                 reqBody.setPayorAcct(objFactory.createTH2THTransferRequestBodyPayorAcct(deposit.getNoAkaunDari()));
                 reqBody.setPayorICNo(objFactory.createTH2THTransferRequestBodyPayorICNo(deposit.getNoKpDari()));             
             }else{            
                 reqBody.setParentAcct(objFactory.createTH2THTransferRequestBodyParentAcct(deposit.getNoAkaun()));
                 reqBody.setParentICNo(objFactory.createTH2THTransferRequestBodyParentICNo(deposit.getNoKp()));
                 reqBody.setPayorAcct(objFactory.createTH2THTransferRequestBodyPayorAcct(deposit.getNoAkaunDari()));
                 reqBody.setPayorICNo(objFactory.createTH2THTransferRequestBodyPayorICNo(deposit.getNoKpDari()));            
             }
                
             BigDecimal amt = deposit.getAmaun();
             amt = amt.multiply(new BigDecimal("100"));
             amt = new BigDecimal(amt.intValue());
             
             reqBody.setAmount(objFactory.createTH2THTransferRequestBodyAmount(amt.toString()));
             reqBody.setPayeeAcct(objFactory.createTH2THTransferRequestBodyPayeeAcct(deposit.getNoAkaunPenerima()));             
             JAXBElement<TH2THTransferRequestBody> jReqBody =  objFactory.createTH2THTransferRequestBody(reqBody);
             req.setBody(jReqBody);
             com.oas.thit._this.transfer.xsd.TH2THTransferResponse result = port.th2ThTransfer(req);             
             Header header = result.getHeader().getValue();
             responseCode = header.getResponseCode().getValue();             
                    
             sejarahTransaksi.setPengguna(pengguna);
             sejarahTransaksi.setTrhMasuk(new Date());
             sejarahTransaksi.setUrusan(kodUrusanDAO.findById(FND_TFR_MSG_ID));
             sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());
             sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
             sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue());
             if ( responseCode.equals(SUCCESSFUL)) {                 
                 TH2THTransferResponseBody res = result.getBody().getValue();
                   if(res != null){                    
                        String txid = header.getTxid().getValue();                       
                        deposit.setNoResit(header.getTxid().getValue().substring(9,25));                       
                        String dt = txid.substring(7, 21);                    
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        deposit.setTarikhTransaksi(dateFormat.parse(dt));
                        deposit.setStsPindahanDis(responseManager.getResponseMessage(SUCCESSFUL, FND_TFR_MSG_ID));
                                                
                        PindahanSimpanan pindahanSimpanan = new PindahanSimpanan();
                        pindahanSimpanan.setAmaun(deposit.getAmaun());
                        pindahanSimpanan.setStatus(deposit.getStsPindahanDis());
                        pindahanSimpanan.setTarikhTransaksi(deposit.getTarikhTransaksi());
                        pindahanSimpanan.setNoAkaunDari(deposit.getNoAkaunDari());
                        pindahanSimpanan.setNama(deposit.getNama());
                        pindahanSimpanan.setNamaPenerima(deposit.getNamaPenerima());
                        pindahanSimpanan.setNoAkaunPenerima(deposit.getNoAkaunPenerima());
                        pindahanSimpanan.setNoResit(deposit.getNoResit());
                        
                        sejarahTransaksi.setDariAkaun(deposit.getNoAkaunDari());
                        sejarahTransaksi.setKepadaAkaun(deposit.getNoAkaunPenerima());
                        sejarahTransaksi.setAmaun(deposit.getAmaun());
                        
                        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);  
                          
                        getContext().getRequest().getSession().setAttribute("PindahanSimpanan",pindahanSimpanan);
                        
                        //edit 1/11/2014
                        
                        String statusTransfer = "success";
                        deposit.setStatusTransfer(statusTransfer);
//                        deposit.setAmaun(amt);
                        getContext().getRequest().getSession().setAttribute("deposit",deposit);
                        sendNotify(deposit);
                        return new JSP("deposit/show_fund_transfer_succesful_msg.jsp");
                        
                }                
             }
              
             addSimpleError("" + responseManager.getResponseMessage(responseCode, FND_TFR_MSG_ID));  
         } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, FND_TFR_MSG_ID));
         } 
        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi); 
        return new JSP("deposit/msg.jsp");         
    }    
    
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    public String sendNotify(Deposit deposit) {
    
        
        String responseCode = "";
        String responseSMS = "";
        
        DecimalFormat formatter = new DecimalFormat("###,###,###.00");
        pengguna = getContext().getCurrentUser();
        //BigDecimal amt = (deposit.getAmaun()).multiply(new BigDecimal("0.01"));
        String amt = formatter.format(deposit.getAmaun());
        //BigDecimal amaun = new BigDecimal(deposit.getAmaun()).multiply(new BigDecimal("0.01"));
        //        String noAkaun = getContext().getRequest().getParameter("noAkaun");
        //        String noKp = getContext().getRequest().getParameter("noKp");
        //        String akaunDari = getContext().getRequest().getParameter("akaunDari");
        //        String noKpDari = getContext().getRequest().getParameter("noKpDari");
        
//        if (!checkAcc(noAkaun, noKp, akaunDari, noKpDari)) {
//            return new JSP("/popup/deposit/tacmsgfailed.jsp");
//        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String dtStr = sdf.format(new Date());        
        
        StringBuilder sb = new StringBuilder(" e-THiJARI: Pindahan Simpanan RM");
        sb.append(amt);
        sb.append(" ke Favourite Account (");
        sb.append(deposit.getNamaPenerima());
        sb.append(") pada ");
        sb.append(dtStr);
        
        
        try { // Call Web Service Operation
                com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
                com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
                // TODO initialize WS operation arguments here
                com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
                com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();

                req.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );

                THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();

                reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(akaunManager.getNoAkaun(pengguna.getNoKp(), "Y")));
                reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(pengguna.getNoKp()));

                JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
                req.setBody(jReqBody);

                // TODO process result here
                com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileQuery(req);
                Header header = result.getHeader().getValue();
                responseCode = header.getResponseCode().getValue();
                if (responseCode.equals(SUCCESSFUL)) {
                    DepositorProfileResponseBody resp = result.getBody().getValue();
                    if ( resp != null ) {
                        //call web service sMS GateWay
                        if(resp.getTHPhoneMobile().getValue().trim()!=null && !resp.getTHPhoneMobile().getValue().trim().equals("")){
                            String mPhone = resp.getTHPhoneMobile().getValue().trim();
//                            StringBuilder sb = new StringBuilder(text);                            
                            sb.append(".Tidak melakukan transaksi? Hubungi ");
                            THISutil tHISutil = tHISutilDAO.findById("101");                            
                            sb.append(tHISutil.getDeskripsi().toString());
                            responseSMS = sMSgatewayManager.sendSMS(mPhone, sb.toString())+","+mPhone;
                        }
                    }
                }

            } catch (Exception ex) {
                LOG.error(ex);
                responseCode = SYSTEM_ERROR;
                addSimpleError("" + responseManager.getResponseMessage(responseCode, PROFILE_ENQ_MSG_ID));  
             }
        return responseSMS;
    }
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++//
    
   

    public List<Akaun> getAccountList() {
        return accountList;
    }

    public void setAccountList(List<Akaun> accountList) {
        this.accountList = accountList;
    }

    public Deposit getDeposit() {
        return deposit;
    }

    public void setDeposit(Deposit deposit) {
        this.deposit = deposit;
    }

    public List<AkaunFav> getAccFavList() {
        return accFavList;
    }

    public void setAccFavList(List<AkaunFav> accFavList) {
        this.accFavList = accFavList;
    }

     public Pengguna getPengguna() {
          return pengguna;
     }

     public void setPengguna(Pengguna pengguna) {
          this.pengguna = pengguna;
     }
}



       
       
